from django.shortcuts import render
from django.http.response import JsonResponse
from django.core import serializers

from .models import *
import json


# Create your views here.


def all_time(request):
    if request.method == "GET":
        db = serializers.serialize("json", Trajec.objects.all())
        return JsonResponse({"status": 0, "data": db, "message": "OK"})
    else:
        return JsonResponse({"status": 1, "data": None, "message": "Need Get Method"})


def get_trajec_from_id(request):
    if request.method == "GET":
        UID = request.GET.get('UID')
        db = [Trajec.objects.get(uid=UID)]
        print('xucong')
        db = serializers.serialize("json", db)
        #f = open('jason.txt', 'w+')
        #f.write(db)
        #f.close
        f = open('jason.txt', 'r')
        content = db#f.read()
        coordinate = content.split(":")[14]
        print(len(coordinate.split("\\")))
        point1 = coordinate.split("\\")[2]
        print(point1)
        dict1 = {}
        num = 0
        for i in coordinate.split("\\"):
            if i.split(",")[3]=='0.0':
                continue
            else:
               num += 1
               str1 = 'point' + str(num) + 'x'
               str2 = 'point' + str(num) + 'y'
               dict1[str1] = i.split(",")[1]
               dict1[str2] = i.split(",")[2]
        dict1['len'] = num
        db1 = json.dumps(dict1)
        #f.close
        return JsonResponse({"status": 0, "data": db1, "message": "OK"})
    else:
        return JsonResponse({"status": 1, "data": None, "message": "Need Get Method"})


def get_vel_from_id(request):
    if request.method == "GET":
        UID = request.GET.get('UID')
        db = [Trajec.objects.get(uid=UID)]
        db = serializers.serialize("json", db)
        f = open('jason.txt', 'r')
        content = db
        meanVel = content.split(":")[len(content.split(":")) - 1]
        coordinate = content.split(":")[14]
        print(len(coordinate.split("\\")))
        point1 = coordinate.split("\\")[2]
        print(point1)
        dict_vel = {}
        num = 0
        for i in coordinate.split("\\"):
            if i.split(",")[3]=='0.0':
                continue
            else:
                num += 1
                vel = 'point' + str(num)
                dict_vel[vel] = i.split(",")[3]
        dict_vel['len'] = num
        dict_vel['averag'] =meanVel.split("}")[0]
        db2 = json.dumps(dict_vel)
        #f.close
        return JsonResponse({"status": 0, "data": db2, "message": "OK"})
    else:
        return JsonResponse({"status": 1, "data": None, "message": "Need Get Method"})